package com.ktjiaoyu.crm.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjiaoyu.crm.mapper.UserMapper;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtils redisUtils;

    private static final String CACHE_KEY_USER="user:";  //缓存key前缀

    @Override
    public User login(String usrName, String usrPassword) {
        //条件构造器
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("usr_name",usrName);
        queryWrapper.eq("usr_password",usrPassword);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public Page<User> getUsersByPages(Page<User> page, Wrapper<User> queryWrapper) {

        return page.setRecords(this.baseMapper.selectUserPages(page,queryWrapper));
    }

    @Override
    public List<User> selectUserPages(Page<User> page, Wrapper<User> queryWrapper) {
        //查询首先从redis中获取数据，如何没有才去数据库中查询
        //Object object = redisUtils.get(CACHE_KEY_USER + ":userList");
        /*if(null != object){
            //redis中有数据，直接返回
            return (List<User>)object;
        }*/
        //redis中没有，查询数据库
        List<User> userList = userMapper.selectUserPages(page,queryWrapper);
        //将数据库中查询的数据存入redis缓存中
        //redisUtils.set(CACHE_KEY_USER + ":userList",userList);
        return userList;
    }


    @Override
    public boolean addUsers(User user) {

        return userMapper.addUsers(user);
    }


    @Cacheable(value = "user",key = "#userId")
    @Override
    public User getUserById(Long userId) {

        return userMapper.selectById(userId);
    }

    @CachePut(value = "user",key = "#user.usrId")
    @Override
    public User updateUser(User user) {
        userMapper.updateById(user);
        return user;
    }

    @CacheEvict(value = "user")
    @Override
    public boolean removeById(Serializable id) {

        return super.removeById(id);
    }
}
